package com.luo.sc.oidc.authserver.controller.login;

import com.luo.sc.oidc.authserver.config.Oauth2ServerProps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 默认登录页 - controller
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-02-14 14:52
 */
@Controller
@Slf4j
public class LoginPageController {

    @Resource
    private Oauth2ServerProps oauth2ServerProps;

    @Resource
    private RequestCache requestCache;


    @GetMapping(value = "${spring.security.oauth2.authserver.login-page-url:/login}")
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {
        //登录页标题
        String clientIdTitle = Optional.ofNullable(this.requestCache.getRequest(request, response))
                .map(savedRequest -> savedRequest.getParameterValues(OAuth2ParameterNames.CLIENT_ID))
                .map(clientIds -> clientIds[0])
                .orElse(this.oauth2ServerProps.getLoginPageTitle());
        model.addAttribute("title", clientIdTitle);
        //登录页form action
        model.addAttribute("loginProcessingUrl", this.oauth2ServerProps.getLoginProcessingUrl());
        //设置是否开启图片验证码
        model.addAttribute("enableCaptcha", this.oauth2ServerProps.getEnableCaptcha());
        model.addAttribute("captchaUrl", this.oauth2ServerProps.getCaptchaUrl());
        return this.oauth2ServerProps.getLoginPageView();
    }

}


